home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / diff / dist / diff3.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-02-23  |  40.8 KB  |  1,505 lines

  1. /* Three-way file comparison program (diff3) for Project GNU
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. /* Written by Randy Smith */
  20.  
  21. #ifdef __STDC__
  22. #define VOID void
  23. #else
  24. #define VOID char
  25. #endif
  26.  
  27. /* 
  28.  * Include files.
  29.  */
  30. #include <stdio.h>
  31. #include <ctype.h>
  32.  
  33. #ifdef USG
  34. #include <fcntl.h>
  35.  
  36. /* Define needed BSD functions in terms of sysV library.  */
  37.  
  38. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  39. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  40. #define bzero(s,n)    memset((s),0,(n))
  41.  
  42. #define dup2(f,t)    (close(t),fcntl((f),F_DUPFD,(t)))
  43.  
  44. #define vfork    fork
  45. #define index    strchr
  46. #define rindex    strrchr
  47. #endif
  48. /*
  49.  * Internal data structures and macros for the diff3 program; includes
  50.  * data structures for both diff3 diffs and normal diffs.
  51.  */
  52.  
  53. /*
  54.  * Different files within a diff
  55.  */
  56. #define    FILE0    0
  57. #define    FILE1    1
  58. #define    FILE2    2
  59.  
  60. /*
  61.  * Three way diffs are build out of two two-way diffs; the file which
  62.  * the two two-way diffs share is:
  63.  */
  64. #define    FILEC    FILE0
  65.  
  66. /* The ranges are indexed by */
  67. #define    START    0
  68. #define    END    1
  69.  
  70. enum diff_type {
  71.   ERROR,            /* Should not be used */
  72.   ADD,                /* Two way diff add */
  73.   CHANGE,            /* Two way diff change */
  74.   DELETE,            /* Two way diff delete */
  75.   DIFF_ALL,            /* All three are different */
  76.   DIFF_1ST,            /* Only the first is different */
  77.   DIFF_2ND,            /* Only the second */
  78.   DIFF_3RD            /* Only the third */
  79. };
  80.  
  81. /* Two-way diff */
  82. struct diff_block {
  83.   int ranges[2][2];            /* Ranges are inclusive */
  84.   char **lines[2];        /* The actual lines (may contain nulls) */
  85.   int *lengths[2];        /* The lengths of the lines (since nulls) */
  86.   struct diff_block *next;
  87. };
  88.  
  89. /* Three-way diff */
  90.  
  91. struct diff3_block {
  92.   enum diff_type correspond;    /* Type of diff */
  93.   int ranges[3][2];            /* Ranges are inclusive */
  94.   char **lines[3];        /* The actual lines (may contain nulls) */
  95.   int *lengths[3];        /* The lengths of the lines (since nulls) */
  96.   struct diff3_block *next;
  97. };
  98.  
  99. /*
  100.  * Access the ranges on a diff block.
  101.  */
  102. #define    D_LOWLINE(diff, filenum)    \
  103.   ((diff)->ranges[filenum][START])
  104. #define    D_HIGHLINE(diff, filenum)    \
  105.   ((diff)->ranges[filenum][END])
  106. #define    D_NUMLINES(diff, filenum)    \
  107.   (D_HIGHLINE((diff), (filenum)) - D_LOWLINE((diff), (filenum)) + 1)
  108.  
  109. /*
  110.  * Access the line numbers in a file in a diff by absolute line number
  111.  * (i.e. line number within the original file).  Note that these are
  112.  * lvalues and can be used for assignment.
  113.  */
  114. #define    D_LINENUM(diff, filenum, linenum)    \
  115.   (*((diff)->lines[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  116. #define    D_LINELEN(diff, filenum, linenum)    \
  117.   (*((diff)->lengths[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  118.  
  119. /*
  120.  * Access the line numbers in a file in a diff by relative line
  121.  * numbers (i.e. line number within the diff itself).  Note that these
  122.  * are lvalues and can be used for assignment.
  123.  */
  124. #define    D_RELNUM(diff, filenum, linenum)    \
  125.   (*((diff)->lines[filenum] + linenum))
  126. #define    D_RELLEN(diff, filenum, linenum)    \
  127.   (*((diff)->lengths[filenum] + linenum))
  128.  
  129. /*
  130.  * And get at them directly, when that should be necessary.
  131.  */
  132. #define    D_LINEARRAY(diff, filenum)    \
  133.   ((diff)->lines[filenum])
  134. #define    D_LENARRAY(diff, filenum)    \
  135.   ((diff)->lengths[filenum])
  136.  
  137. /*
  138.  * Next block.
  139.  */
  140. #define    D_NEXT(diff)    ((diff)->next)
  141.  
  142. /*
  143.  * Access the type of a diff3 block.
  144.  */
  145. #define    D3_TYPE(diff)    ((diff)->correspond)
  146.  
  147. /*
  148.  * Line mappings based on diffs.  The first maps off the top of the
  149.  * diff, the second off of the bottom.
  150.  */
  151. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, lineno)    \
  152.   ((lineno)                        \
  153.    - D_HIGHLINE ((diff), (fromfile))            \
  154.    + D_HIGHLINE ((diff), (tofile)))
  155.  
  156. #define    D_LOW_MAPLINE(diff, fromfile, tofile, lineno)    \
  157.   ((lineno)                        \
  158.    - D_LOWLINE ((diff), (fromfile))            \
  159.    + D_LOWLINE ((diff), (tofile)))
  160.  
  161. /*
  162.  * General memory allocation function.
  163.  */
  164. #define    ALLOCATE(number, type)    \
  165.   (type *) xmalloc ((number) * sizeof (type))
  166.  
  167. /*
  168.  * Options variables for flags set on command line.
  169.  *
  170.  * EDSCRIPT: Write out an ed script instead of the standard diff3 format.
  171.  *
  172.  * FLAGGING: Indicates that in the case of overlapping diffs (type
  173.  * DIFF_ALL), the lines which would normally be deleted from file 1
  174.  * should be preserved with a special flagging mechanism.
  175.  *
  176.  * DONT_WRITE_OVERLAP: 1 if information for overlapping diffs should
  177.  * not be output.
  178.  *
  179.  * DONT_WRITE_SIMPLE: 1 if information for non-overlapping diffs
  180.  * should not be output. 
  181.  *
  182.  * FINALWRITE: 1 if a :wq should be included at the end of the script
  183.  * to write out the file being edited.
  184.  */
  185. int edscript;
  186. int flagging;
  187. int dont_write_overlap;
  188. int dont_write_simple;
  189. int finalwrite;
  190.  
  191. extern int optind;
  192.  
  193. char *argv0;
  194.  
  195. /*
  196.  * Forward function declarations.
  197.  */
  198. struct diff_block *process_diff ();
  199. struct diff3_block *make_3way_diff ();
  200. void output_diff3 ();
  201. int output_diff3_edscript ();
  202. void usage ();
  203.  
  204. struct diff3_block *using_to_diff3_block ();
  205. int copy_stringlist ();
  206. struct diff3_block *create_diff3_block ();
  207. int compare_line_list ();
  208.  
  209. int read_diff ();
  210. enum diff_type process_diff_control ();
  211. char *scan_diff_line ();
  212.  
  213. struct diff3_block *reverse_diff3_blocklist ();
  214.  
  215. VOID *xmalloc ();
  216. VOID *xrealloc ();
  217.  
  218. /*
  219.  * No options take arguments.  "i" is my own addition; it stands for
  220.  * "include write command", to emulate system V behavior.
  221.  */
  222. #define    ARGSTRING    "eix3EX"
  223.  
  224. char diff_program[] = DIFF_PROGRAM;
  225.  
  226. /*
  227.  * Main program.  Calls diff twice on two pairs of input files,
  228.  * combines the two diffs, and outputs them.
  229.  */
  230. main (argc, argv)
  231.      int argc;
  232.      char **argv;
  233. {
  234.   int c;
  235.   int mapping [3];
  236.   int shiftmap;
  237.   int incompat;
  238.   int overlap_count;
  239.   struct diff_block *thread1, *thread2;
  240.   struct diff3_block *diff;
  241.  
  242.   edscript = flagging = dont_write_overlap
  243.     = dont_write_simple = finalwrite = 0;
  244.   incompat = shiftmap = 0;
  245.  
  246.   argv0 = argv[0];
  247.   
  248.   while ((c = getopt (argc, argv, ARGSTRING)) != EOF)
  249.     {
  250.       edscript = 1;
  251.       switch (c)
  252.     {
  253.     case 'x':
  254.       dont_write_simple = 1;
  255.       incompat++;
  256.       break;
  257.     case '3':
  258.       dont_write_overlap = 1;
  259.       incompat++;
  260.       break;
  261.     case 'i':
  262.       finalwrite = 1;
  263.       incompat++;
  264.       break;
  265.     case 'X':
  266.       dont_write_simple = 1;
  267.       /* Falls through */
  268.     case 'E':
  269.       flagging = 1;
  270.       /* Falls through */
  271.     case 'e':
  272.       incompat++;
  273.       break;
  274.     case '?':
  275.     default:
  276.       usage ();
  277.       /* NOTREACHED */
  278.     }
  279.     }
  280.  
  281.   if (incompat > 1)        /* Make sure you only have one of a */
  282.                 /* set of arguments */
  283.     usage ();
  284.   
  285.   if (argc - optind != 3)
  286.     usage ();
  287.  
  288.   if (*argv[optind] == '-' && *(argv[optind] + 1) == '\0')
  289.     {
  290.       /* Sigh.  We've got standard input as the first arg. We can't */
  291.       /* call diff twice on stdin */
  292.       mapping [0] = 1;
  293.       mapping [1] = 2;
  294.       mapping [2] = 0;
  295.       shiftmap = 1;
  296.     }
  297.   else
  298.     {
  299.       /* Normal, what you'd expect */
  300.       mapping [0] = 0;
  301.       mapping [1] = 1;
  302.       mapping [2] = 2;
  303.       shiftmap = 0;
  304.     }
  305.  
  306.   if (shiftmap)
  307.     {
  308.       thread1 = process_diff (argv[optind + 2], argv[optind]);
  309.       thread2 = process_diff (argv[optind + 2], argv[optind + 1]);
  310.     }
  311.   else
  312.     {
  313.       thread1 = process_diff (argv[optind], argv[optind + 1]);
  314.       thread2 = process_diff (argv[optind], argv[optind + 2]);
  315.     }
  316.   diff = make_3way_diff (thread1, thread2);
  317.   if (edscript)
  318.     overlap_count
  319.       = output_diff3_edscript (stdout, diff, mapping, argv[optind],
  320.                    argv[optind + 1], argv[optind + 2]);
  321.   else
  322.     output_diff3 (stdout, diff, mapping);
  323.  
  324.   if (edscript && overlap_count > 0)
  325.     /* We don't return overlap_count since it could overflow;
  326.        exit status is just 8 bits.  */
  327.     exit (1);
  328.   exit (0);
  329. }
  330.       
  331. /*
  332.  * Explain, patiently and kindly, how to use this program.  Then exit.
  333.  */
  334. void
  335. usage ()
  336. {
  337.   fprintf (stderr, "Usage:\t%s [ -exEX3 ] [ -i ] file1 file2 file3\n",
  338.        argv0);
  339.   fprintf (stderr, "\tOnly one of [exEX3] allowed\n");
  340.   exit (1);
  341. }
  342.  
  343. /*
  344.  * Routines that combine the two diffs together into one.  The
  345.  * algorithm used follows:
  346.  *
  347.  *   File0 is shared in common between the two diffs.
  348.  *   Diff01 is the diff between 0 and 1.
  349.  *   Diff02 is the diff between 0 and 2.
  350.  *
  351.  *     1) Find the range for the first block in File0.
  352.  *          a) Take the lowest of the two ranges (in File0) in the two
  353.  *             current blocks (one from each diff) as being the low
  354.  *             water mark.  Assign the upper end of this block as
  355.  *             being the high water mark and move the current block up
  356.  *             one.  Mark the block just moved over as to be used.
  357.  *        b) Check the next block in the diff that the high water
  358.  *             mark is *not* from.  
  359.  *           
  360.  *           *If* the high water mark is above
  361.  *             the low end of the range in that block, 
  362.  * 
  363.  *               mark that block as to be used and move the current
  364.  *                 block up.  Set the high water mark to the max of
  365.  *                 the high end of this block and the current.  Repeat b.
  366.  * 
  367.  *       2) Find the corresponding ranges in Files1 (from the blocks
  368.  *          in diff01; line per line outside of diffs) and in File2.
  369.  *          Create a diff3_block, reserving space as indicated by the ranges.
  370.  *        
  371.  *     3) Copy all of the pointers for file0 in.  At least for now,
  372.  *          do bcmp's between corresponding strings in the two diffs.
  373.  *        
  374.  *     4) Copy all of the pointers for file1 and 2 in.  Get what you
  375.  *          need from file0 (when there isn't a diff block, it's
  376.  *          identical to file0 within the range between diff blocks).
  377.  *        
  378.  *     5) If the diff blocks you used came from only one of the two
  379.  *         strings of diffs, then that file (i.e. the one other than
  380.  *         file 0 in that diff) is the odd person out.  If you used
  381.  *         diff blocks from both sets, check to see if files 1 and 2 match:
  382.  *        
  383.  *            Same number of lines?  If so, do a set of bcmp's (if a
  384.  *          bcmp matches; copy the pointer over; it'll be easier later
  385.  *          if you have to do any compares).  If they match, 1 & 2 are
  386.  *          the same.  If not, all three different.
  387.  * 
  388.  *   Then you do it again, until you run out of blocks. 
  389.  * 
  390.  */
  391.  
  392. /* 
  393.  * This routine makes a three way diff (chain of diff3_block's) from two
  394.  * two way diffs (chains of diff_block's).  It is assumed that each of
  395.  * the two diffs passed are off of the same file (i.e. that each of the
  396.  * diffs were made "from" the same file).  The three way diff pointer
  397.  * returned will have numbering 0--the common file, 1--the other file
  398.  * in diff1, and 2--the other file in diff2.
  399.  */
  400. struct diff3_block *
  401. make_3way_diff (thread1, thread2)
  402.      struct diff_block *thread1, *thread2;
  403. {
  404. /*
  405.  * This routine works on the two diffs passed to it as threads.
  406.  * Thread number 0 is diff1, thread number 1 is diff2.  The USING
  407.  * array is set to the base of the list of blocks to be used to
  408.  * construct each block of the three way diff; if no blocks from a
  409.  * particular thread are to be used, that element of the using array
  410.  * is set to 0.  The elements LAST_USING array are set to the last
  411.  * elements on each of the using lists.
  412.  *
  413.  * The HIGH_WATER_MARK is set to the highest line number in File 0
  414.  * described in any of the diffs in either of the USING lists.  The
  415.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  416.  * and BASE_WATER_THREAD describe the lowest line number in File 0
  417.  * described in any of the diffs in either of the USING lists.  The
  418.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  419.  * taken. 
  420.  *
  421.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  422.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  423.  * higher water, and should always be equal to
  424.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  425.  * in which the OTHER_DIFF is, and hence should always be equal to
  426.  * HIGH_WATER_THREAD ^ 0x1.
  427.  *
  428.  * The variable LAST_DIFF is kept set to the last diff block produced
  429.  * by this routine, for line correspondence purposes between that diff
  430.  * and the one currently being worked on.  It is initialized to
  431.  * ZERO_DIFF before any blocks have been created.
  432.  */
  433.  
  434.   struct diff_block
  435.     *using[2],
  436.     *last_using[2],
  437.     *current[2];
  438.  
  439.   int
  440.     high_water_mark;
  441.  
  442.   int
  443.     high_water_thread,
  444.     base_water_thread,
  445.     other_thread;
  446.  
  447.   struct diff_block
  448.     *high_water_diff,
  449.     *other_diff;
  450.  
  451.   struct diff3_block
  452.     *result,
  453.     *tmpblock,
  454.     *result_last,
  455.     *last_diff;
  456.  
  457.   static struct diff3_block zero_diff = {
  458.       ERROR,
  459.       { {0, 0}, {0, 0}, {0, 0} },
  460.       { (char **) 0, (char **) 0, (char **) 0 },
  461.       { (int *) 0, (int *) 0, (int *) 0 },
  462.       (struct diff3_block *) 0
  463.       };
  464.  
  465.   /* Initialization */
  466.   result = result_last = (struct diff3_block *) 0;
  467.   current[0] = thread1; current[1] = thread2;
  468.   last_diff = &zero_diff;
  469.  
  470.   /* Sniff up the threads until we reach the end */
  471.  
  472.   while (current[0] || current[1])
  473.     {
  474.       using[0] = using[1] = last_using[0] = last_using[1] =
  475.     (struct diff_block *) 0;
  476.  
  477.       /* Setup low and high water threads, diffs, and marks.  */
  478.       if (!current[0])
  479.     base_water_thread = 1;
  480.       else if (!current[1])
  481.     base_water_thread = 0;
  482.       else
  483.     base_water_thread =
  484.       (D_LOWLINE (current[0], FILE0) > D_LOWLINE (current[1], FILE0));
  485.  
  486.       high_water_thread = base_water_thread;
  487.       
  488.       high_water_diff = current[high_water_thread];
  489.     
  490. #if 0
  491.       /* low and high waters start off same diff */
  492.       base_water_mark = D_LOWLINE (high_water_diff, FILE0);
  493. #endif
  494.  
  495.       high_water_mark = D_HIGHLINE (high_water_diff, FILE0);
  496.  
  497.       /* Make the diff you just got info from into the using class */
  498.       using[high_water_thread]
  499.     = last_using[high_water_thread]
  500.     = high_water_diff;
  501.       current[high_water_thread] = high_water_diff->next;
  502.       last_using[high_water_thread]->next
  503.     = (struct diff_block *) 0;
  504.  
  505.       /* And mark the other diff */
  506.       other_thread = high_water_thread ^ 0x1;
  507.       other_diff = current[other_thread];
  508.  
  509.       /* Shuffle up the ladder, checking the other diff to see if it
  510.          needs to be incorporated */
  511.       while (other_diff
  512.          && D_LOWLINE (other_diff, FILE0) <= high_water_mark + 1)
  513.     {
  514.  
  515.       /* Incorporate this diff into the using list.  Note that
  516.          this doesn't take it off the current list */
  517.       if (using[other_thread])
  518.         last_using[other_thread]->next = other_diff;
  519.       else
  520.         using[other_thread] = other_diff;
  521.       last_using[other_thread] = other_diff;
  522.  
  523.       /* Take it off the current list.  Note that this following
  524.          code assumes that other_diff enters it equal to
  525.          current[high_water_thread ^ 0x1] */
  526.       current[other_thread]
  527.         = current[other_thread]->next;
  528.       other_diff->next
  529.         = (struct diff_block *) 0;
  530.  
  531.       /* Set the high_water stuff
  532.          If this comparison is equal, then this is the last pass
  533.          through this loop; since diff blocks within a given
  534.          thread cannot overlap, the high_water_mark will be
  535.          *below* the range_start of either of the next diffs. */
  536.  
  537.       if (high_water_mark < D_HIGHLINE (other_diff, FILE0))
  538.         {
  539.           high_water_thread ^= 1;
  540.           high_water_diff = other_diff;
  541.           high_water_mark = D_HIGHLINE (other_diff, FILE0);
  542.         }
  543.  
  544.       /* Set the other diff */
  545.       other_thread = high_water_thread ^ 0x1;
  546.       other_diff = current[other_thread];
  547.     }
  548.  
  549.       /* The using lists contain a list of all of the blocks to be
  550.          included in this diff3_block.  Create it.  */
  551.  
  552.       tmpblock = using_to_diff3_block (using, last_using,
  553.                        base_water_thread, high_water_thread,
  554.                        last_diff);
  555.  
  556.       if (!tmpblock)
  557.     fatal ("internal: screwup in format of diff blocks");
  558.  
  559.       /* Put it on the list */
  560.       if (result)
  561.     result_last->next = tmpblock;
  562.       else
  563.     result = tmpblock;
  564.       result_last = tmpblock;
  565.  
  566.       /* Setup corresponding lines correctly */
  567.       last_diff = tmpblock;
  568.     }
  569.   return result;
  570. }
  571.  
  572. /*
  573.  * using_to_diff3_block:
  574.  *   This routine takes two lists of blocks (from two separate diff
  575.  * threads) and puts them together into one diff3 block.
  576.  * It then returns a pointer to this diff3 block or 0 for failure.
  577.  *
  578.  * All arguments besides using are for the convenience of the routine;
  579.  * they could be derived from the using array.
  580.  * LAST_USING is a pair of pointers to the last blocks in the using
  581.  * structure.
  582.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  583.  * and highest line numbers for File0.
  584.  * last_diff contains the last diff produced in the calling routine.
  585.  * This is used for lines mappings which would still be identical to
  586.  * the state that diff ended in.
  587.  *
  588.  * A distinction should be made in this routine between the two diffs
  589.  * that are part of a normal two diff block, and the three diffs that
  590.  * are part of a diff3_block.
  591.  */
  592. struct diff3_block *
  593. using_to_diff3_block (using, last_using, low_thread, high_thread, last_diff)
  594.      struct diff_block
  595.        *using[2],
  596.        *last_using[2];
  597.      int low_thread, high_thread;
  598.      struct diff3_block *last_diff;
  599. {
  600.   int lowc, highc, low1, high1, low2, high2;
  601.   struct diff3_block *result;
  602.   struct diff_block *ptr;
  603.   int i;
  604.   int current0line;
  605.   
  606.   /* Find the range in file0 */
  607.   lowc = using[low_thread]->ranges[0][START];
  608.   highc = last_using[high_thread]->ranges[0][END];
  609.  
  610.   /* Find the ranges in the other files.
  611.      If using[x] is null, that means that the file to which that diff
  612.      refers is equivalent to file 0 over this range */
  613.   
  614.   if (using[0])
  615.     {
  616.       low1 = D_LOW_MAPLINE (using[0], FILE0, FILE1, lowc);
  617.       high1 = D_HIGH_MAPLINE (last_using[0], FILE0, FILE1, highc); 
  618.     }
  619.   else
  620.     {
  621.       low1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, lowc);
  622.       high1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, highc);
  623.     }
  624.  
  625.   /*
  626.    * Note that in the following, we use file 1 relative to the diff,
  627.    * and file 2 relative to the corresponding lines struct.
  628.    */
  629.   if (using[1])
  630.     {
  631.       low2 = D_LOW_MAPLINE (using[1], FILE0, FILE1, lowc);
  632.       high2 = D_HIGH_MAPLINE (last_using[1], FILE0, FILE1, highc); 
  633.     }
  634.   else
  635.     {
  636.       low2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, lowc);
  637.       high2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, highc);
  638.     }
  639.  
  640.   /* Create a block with the appropriate sizes */
  641.   result = create_diff3_block (lowc, highc, low1, high1, low2, high2);
  642.  
  643.   /* Copy over all of the information for File 0.  Return with a zero
  644.      if any of the compares failed. */
  645.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  646.     {
  647.       int result_offset = D_LOWLINE (ptr, FILE0) - lowc;
  648.       int copy_size
  649.     = D_HIGHLINE (ptr, FILE0) - D_LOWLINE (ptr, FILE0) + 1;
  650.       
  651.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  652.                 D_LENARRAY (ptr, FILE0),
  653.                 D_LINEARRAY (result, FILEC) + result_offset,
  654.                 D_LENARRAY (result, FILEC) + result_offset,
  655.                 copy_size))
  656.     return 0;
  657.     }
  658.  
  659.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  660.     {
  661.       int result_offset = D_LOWLINE (ptr, FILEC) - lowc;
  662.       int copy_size
  663.     = D_HIGHLINE (ptr, FILEC) - D_LOWLINE (ptr, FILEC) + 1;
  664.       
  665.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  666.                 D_LENARRAY (ptr, FILE0),
  667.                 D_LINEARRAY (result, FILEC) + result_offset,
  668.                 D_LENARRAY (result, FILEC) + result_offset,
  669.                 copy_size))
  670.     return 0;
  671.     }
  672.  
  673.   /* Copy stuff for file 1.  First deal with anything that might be
  674.      before the first diff. */
  675.  
  676.   for (i = 0;
  677.        i + low1 < (using[0] ? D_LOWLINE (using[0], FILE1) : high1 + 1);
  678.        i++)
  679.     {
  680.       D_RELNUM (result, FILE1, i) = D_RELNUM (result, FILEC, i);
  681.       D_RELLEN (result, FILE1, i) = D_RELLEN (result, FILEC, i);
  682.     }
  683.   
  684.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  685.     {
  686.       int result_offset = D_LOWLINE (ptr, FILE1) - low1;
  687.       int copy_size
  688.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  689.  
  690.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  691.                 D_LENARRAY (ptr, FILE1),
  692.                 D_LINEARRAY (result, FILE1) + result_offset,
  693.                 D_LENARRAY (result, FILE1) + result_offset,
  694.                 copy_size))
  695.     return 0;
  696.  
  697.       /* Catch the lines between here and the next diff */
  698.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  699.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low1;
  700.        i < (D_NEXT (ptr) ?
  701.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  702.         high1 + 1) - low1;
  703.        i++)
  704.     {
  705.       D_RELNUM (result, FILE1, i)
  706.         = D_RELNUM (result, FILEC, current0line);
  707.       D_RELLEN (result, FILE1, i)
  708.         = D_RELLEN (result, FILEC, current0line++);
  709.     }
  710.     }
  711.  
  712.   /* Copy stuff for file 2.  First deal with anything that might be
  713.      before the first diff. */
  714.  
  715.   for (i = 0;
  716.        i + low2 < (using[1] ? D_LOWLINE (using[1], FILE1) : high2 + 1);
  717.        i++)
  718.     {
  719.       D_RELNUM (result, FILE2, i) = D_RELNUM (result, FILEC, i);
  720.       D_RELLEN (result, FILE2, i) = D_RELLEN (result, FILEC, i);
  721.     }
  722.   
  723.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  724.     {
  725.       int result_offset = D_LOWLINE (ptr, FILE1) - low2;
  726.       int copy_size
  727.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  728.  
  729.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  730.                 D_LENARRAY (ptr, FILE1),
  731.                 D_LINEARRAY (result, FILE2) + result_offset,
  732.                 D_LENARRAY (result, FILE2) + result_offset,
  733.                 copy_size))
  734.     return 0;
  735.  
  736.       /* Catch the lines between here and the next diff */
  737.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  738.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low2;
  739.        i < (D_NEXT (ptr) ?
  740.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  741.         high2 + 1) - low2;
  742.        i++)
  743.     {
  744.       D_RELNUM (result, FILE2, i)
  745.         = D_RELNUM (result, FILEC, current0line);
  746.       D_RELLEN (result, FILE2, i)
  747.         = D_RELLEN (result, FILEC, current0line++);
  748.     }
  749.     }
  750.  
  751.   /* Set correspond */
  752.   if (!using[0])
  753.     D3_TYPE (result) = DIFF_3RD;
  754.   else if (!using[1])
  755.     D3_TYPE (result) = DIFF_2ND;
  756.   else
  757.     {
  758.       int nl1
  759.     = D_HIGHLINE (result, FILE1) - D_LOWLINE (result, FILE1) + 1;
  760.       int nl2
  761.     = D_HIGHLINE (result, FILE2) - D_LOWLINE (result, FILE2) + 1;
  762.  
  763.       if (nl1 != nl2
  764.       || !compare_line_list (D_LINEARRAY (result, FILE1),
  765.                  D_LENARRAY (result, FILE1),
  766.                  D_LINEARRAY (result, FILE2),
  767.                  D_LENARRAY (result, FILE2),
  768.                  nl1))
  769.     D3_TYPE (result) = DIFF_ALL;
  770.       else
  771.     D3_TYPE (result) = DIFF_1ST;
  772.     }
  773.   
  774.   return result;
  775. }
  776.  
  777. /*
  778.  * This routine copies pointers from a list of strings to a different list
  779.  * of strings.  If a spot in the second list is already filled, it
  780.  * makes sure that it is filled with the same string; if not it
  781.  * returns 0, the copy incomplete.
  782.  * Upon successful completion of the copy, it returns 1.
  783.  */
  784. int
  785. copy_stringlist (fromptrs, fromlengths, toptrs, tolengths, copynum)
  786.      char *fromptrs[], *toptrs[];
  787.      int *fromlengths, *tolengths;
  788.      int copynum;
  789. {
  790.   register char
  791.     **f = fromptrs,
  792.     **t = toptrs;
  793.   register int
  794.     *fl = fromlengths,
  795.     *tl = tolengths;
  796.   
  797.   while (copynum--)
  798.     {
  799.       if (*t)
  800.     { if (*fl != *tl || bcmp (*f, *t, *fl)) return 0; }
  801.       else
  802.     { *t = *f ; *tl = *fl; }
  803.  
  804.       t++; f++; tl++; fl++;
  805.     }
  806.   return 1;
  807. }
  808.  
  809. /*
  810.  * Create a diff3_block, with ranges as specified in the arguments.
  811.  * Allocate the arrays for the various pointers (and zero them) based
  812.  * on the arguments passed.  Return the block as a result.
  813.  */
  814. struct diff3_block *
  815. create_diff3_block (low0, high0, low1, high1, low2, high2)
  816.      register int low0, high0, low1, high1, low2, high2;
  817. {
  818.   struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  819.   int numlines;
  820.  
  821.   D3_TYPE (result) = ERROR;
  822.   D_NEXT (result) = 0;
  823.  
  824.   /* Assign ranges */
  825.   D_LOWLINE (result, FILE0) = low0;
  826.   D_HIGHLINE (result, FILE0) = high0;
  827.   D_LOWLINE (result, FILE1) = low1;
  828.   D_HIGHLINE (result, FILE1) = high1;
  829.   D_LOWLINE (result, FILE2) = low2;
  830.   D_HIGHLINE (result, FILE2) = high2;
  831.  
  832.   /* Allocate and zero space */
  833.   numlines = D_NUMLINES (result, FILE0);
  834.   if (numlines)
  835.     {
  836.       D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  837.       D_LENARRAY (result, FILE0) = ALLOCATE (numlines, int);
  838.       bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  839.       bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (int)));
  840.     }
  841.   else
  842.     {
  843.       D_LINEARRAY (result, FILE0) = (char **) 0;
  844.       D_LENARRAY (result, FILE0) = (int *) 0;
  845.     }
  846.  
  847.   numlines = D_NUMLINES (result, FILE1);
  848.   if (numlines)
  849.     {
  850.       D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  851.       D_LENARRAY (result, FILE1) = ALLOCATE (numlines, int);
  852.       bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  853.       bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (int)));
  854.     }
  855.   else
  856.     {
  857.       D_LINEARRAY (result, FILE1) = (char **) 0;
  858.       D_LENARRAY (result, FILE1) = (int *) 0;
  859.     }
  860.  
  861.   numlines = D_NUMLINES (result, FILE2);
  862.   if (numlines)
  863.     {
  864.       D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  865.       D_LENARRAY (result, FILE2) = ALLOCATE (numlines, int);
  866.       bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  867.       bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (int)));
  868.     }
  869.   else
  870.     {
  871.       D_LINEARRAY (result, FILE2) = (char **) 0;
  872.       D_LENARRAY (result, FILE2) = (int *) 0;
  873.     }
  874.  
  875.   /* Return */
  876.   return result;
  877. }
  878.  
  879. /*
  880.  * Compare two lists of lines of text.
  881.  * Return 1 if they are equivalent, 0 if not.
  882.  */
  883. int
  884. compare_line_list (list1, lengths1, list2, lengths2, nl)
  885.      char *list1[], *list2[];
  886.      int *lengths1, *lengths2;
  887.      int nl;
  888. {
  889.   char
  890.     **l1 = list1,
  891.     **l2 = list2;
  892.   int
  893.     *lgths1 = lengths1,
  894.     *lgths2 = lengths2;
  895.   
  896.   while (nl--)
  897.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  898.     || bcmp (*l1++, *l2++, *lgths1++))
  899.       return 0;
  900.   return 1;
  901. }
  902.  
  903. /* 
  904.  * Routines to input and parse two way diffs.
  905.  */
  906.  
  907. extern char **environ;
  908.  
  909. #define    DIFF_CHUNK_SIZE    10000
  910.  
  911. struct diff_block *
  912. process_diff (filea, fileb)
  913.      char *filea, *fileb;
  914. {
  915.   char *diff_contents;
  916.   int diff_size;
  917.   char *scan_diff;
  918.   enum diff_type dt;
  919.   int i;
  920.   struct diff_block *block_list, *block_list_end, *bptr;
  921.  
  922.   diff_size = read_diff (filea, fileb, &diff_contents);
  923.   scan_diff = diff_contents;
  924.   bptr = block_list_end = block_list = (struct diff_block *) 0;
  925.  
  926.   while (scan_diff - diff_contents < diff_size)
  927.     {
  928.       bptr = ALLOCATE (1, struct diff_block);
  929.       bptr->next = 0;
  930.       bptr->lines[0] = bptr->lines[1] = (char **) 0;
  931.       bptr->lengths[0] = bptr->lengths[1] = (int *) 0;
  932.       
  933.       dt = process_diff_control (&scan_diff, bptr);
  934.       if (dt == ERROR) fatal ("Bad format in diff output");
  935.       if (*scan_diff != '\n') fatal ("Bad format in diff output");
  936.       scan_diff++;
  937.       
  938.       /* Force appropriate ranges to be null, if necessary */
  939.       switch (dt)
  940.     {
  941.     case ADD:
  942.       bptr->ranges[0][0]++;
  943.       break;
  944.     case DELETE:
  945.       bptr->ranges[1][0]++;
  946.       break;
  947.     case CHANGE:
  948.       break;
  949.     default:
  950.       fatal ("internal: Bad diff type in process_diff");
  951.       break;
  952.     }
  953.       
  954.       /* Allocate space for the pointers for the lines from filea, and
  955.      parcel them out among these pointers */
  956.       if (dt != ADD)
  957.     {
  958.       bptr->lines[0] = ALLOCATE ((bptr->ranges[0][END]
  959.                       - bptr->ranges[0][START] + 1),
  960.                      char *);
  961.       bptr->lengths[0] = ALLOCATE ((bptr->ranges[0][END]
  962.                     - bptr->ranges[0][START] + 1),
  963.                        int);
  964.       for (i = 0; i <= (bptr->ranges[0][END]
  965.                 - bptr->ranges[0][START]); i++)
  966.         scan_diff = scan_diff_line (scan_diff,
  967.                     &(bptr->lines[0][i]),
  968.                     &(bptr->lengths[0][i]),
  969.                     diff_contents + diff_size,
  970.                     '<');
  971.     }
  972.       
  973.       /* Get past the separator for changes */
  974.       if (dt == CHANGE)
  975.     {
  976.       if (strncmp (scan_diff, "---\n", 4))
  977.         fatal ("Bad diff format: bad change separator");
  978.       scan_diff += 4;
  979.     }
  980.       
  981.       /* Allocate space for the pointers for the lines from fileb, and
  982.      parcel them out among these pointers */
  983.       if (dt != DELETE)
  984.     {
  985.       bptr->lines[1] = ALLOCATE ((bptr->ranges[1][END]
  986.                       - bptr->ranges[1][START] + 1),
  987.                      char *);
  988.       bptr->lengths[1] = ALLOCATE ((bptr->ranges[1][END]
  989.                     - bptr->ranges[1][START] + 1),
  990.                        int);
  991.       for (i = 0; i <= (bptr->ranges[1][END]
  992.                 - bptr->ranges[1][START]); i++)
  993.         scan_diff = scan_diff_line (scan_diff,
  994.                     &(bptr->lines[1][i]),
  995.                     &(bptr->lengths[1][i]),
  996.                     diff_contents + diff_size,
  997.                     '>');
  998.     }
  999.       
  1000.       /* Place this block on the blocklist */
  1001.       if (block_list_end)
  1002.     block_list_end->next = bptr;
  1003.       else
  1004.     block_list = bptr;
  1005.       
  1006.       block_list_end = bptr;
  1007.       
  1008.     }
  1009.  
  1010.   if (scan_diff - diff_contents != diff_size)
  1011.     fatal ("bad diff format; incomplete last line");
  1012.  
  1013.   return block_list;
  1014. }
  1015.  
  1016. /*
  1017.  * This routine will parse a normal format diff control string.  It
  1018.  * returns the type of the diff (ERROR if the format is bad).  All of
  1019.  * the other important information is filled into to the structure
  1020.  * pointed to by db, and the string pointer (whose location is passed
  1021.  * to this routine) is updated to point beyond the end of the string
  1022.  * parsed.  Note that only the ranges in the diff_block will be set by
  1023.  * this routine.
  1024.  *
  1025.  * If some specific pair of numbers has been reduced to a single
  1026.  * number, then both corresponding numbers in the diff block are set
  1027.  * to that number.  In general these numbers are interpetted as ranges
  1028.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1029.  * assumed that these will be special cased in a superior routine.  
  1030.  */
  1031.  
  1032. enum diff_type
  1033. process_diff_control (string, db)
  1034.      char **string;
  1035.      struct diff_block *db;
  1036. {
  1037.   char *s = *string;
  1038.   int holdnum;
  1039.   enum diff_type type;
  1040.  
  1041. /* These macros are defined here because they can use variables
  1042.    defined in this function.  Don't try this at home kids, we're
  1043.    trained professionals!
  1044.  
  1045.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1046.    that READNUM can only read positive, integral numbers */
  1047.  
  1048. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1049. #define    READNUM(s, num)    \
  1050.     { if (!isdigit (*s)) return ERROR; holdnum = 0;    \
  1051.       do { holdnum = (*s++ - '0' + holdnum * 10); }    \
  1052.       while (isdigit (*s)); (num) = holdnum; }
  1053.  
  1054.   /* Read first set of digits */
  1055.   SKIPWHITE (s);
  1056.   READNUM (s, db->ranges[0][START]);
  1057.  
  1058.   /* Was that the only digit? */
  1059.   SKIPWHITE(s);
  1060.   if (*s == ',')
  1061.     {
  1062.       /* Get the next digit */
  1063.       s++;
  1064.       READNUM (s, db->ranges[0][END]);
  1065.     }
  1066.   else
  1067.     db->ranges[0][END] = db->ranges[0][START];
  1068.  
  1069.   /* Get the letter */
  1070.   SKIPWHITE (s);
  1071.   switch (*s)
  1072.     {
  1073.     case 'a':
  1074.       type = ADD;
  1075.       break;
  1076.     case 'c':
  1077.       type = CHANGE;
  1078.       break;
  1079.     case 'd':
  1080.       type = DELETE;
  1081.       break;
  1082.     default:
  1083.       return ERROR;            /* Bad format */
  1084.     }
  1085.   s++;                /* Past letter */
  1086.   
  1087.   /* Read second set of digits */
  1088.   SKIPWHITE (s);
  1089.   READNUM (s, db->ranges[1][START]);
  1090.  
  1091.   /* Was that the only digit? */
  1092.   SKIPWHITE(s);
  1093.   if (*s == ',')
  1094.     {
  1095.       /* Get the next digit */
  1096.       s++;
  1097.       READNUM (s, db->ranges[1][END]);
  1098.       SKIPWHITE (s);        /* To move to end */
  1099.     }
  1100.   else
  1101.     db->ranges[1][END] = db->ranges[1][START];
  1102.  
  1103.   *string = s;
  1104.   return type;
  1105. }
  1106.  
  1107. int
  1108. read_diff (filea, fileb, output_placement)
  1109.      char *filea, *fileb;
  1110.      char **output_placement;
  1111. {
  1112.   char *argv[4];
  1113.   int fds[2];
  1114.   char *diff_result;
  1115.   long current_chunk_size;
  1116.   int bytes;
  1117.   int total;
  1118.  
  1119.   argv[0] = diff_program;
  1120.   argv[1] = filea;
  1121.   argv[2] = fileb;
  1122.   argv[3] = (char *) 0;
  1123.  
  1124.   pipe (fds);
  1125.  
  1126.   if (!fork ())
  1127.     {
  1128.       /* Child */
  1129.       dup2 (fds[1], 1);        /* Make stdout the pipe to the parent */
  1130.       /* Leave stdin alone; the diff may need it */
  1131.       execve (diff_program, argv, environ);
  1132.       perror_with_exit ("Exec failed");
  1133.     }
  1134.  
  1135.   close (fds[1]);        /* Prevent erroneous lack of EOF */
  1136.   current_chunk_size = DIFF_CHUNK_SIZE;
  1137.   diff_result = (char *) xmalloc (current_chunk_size);
  1138.   total = 0;
  1139.   do {
  1140.     bytes = myread (fds[0],
  1141.             diff_result + total,
  1142.             current_chunk_size - total);
  1143.     total += bytes;
  1144.     if (total == current_chunk_size)
  1145.       diff_result = (char *) xrealloc (diff_result, (current_chunk_size *= 2));
  1146.   } while (bytes);
  1147.  
  1148.   *output_placement = diff_result;
  1149.  
  1150.   return total;
  1151. }
  1152.  
  1153.  
  1154. /*
  1155.  * Scan a regular diff line (consisting of > or <, followed by a
  1156.  * space, followed by text (including nulls) up to a newline.
  1157.  *
  1158.  * This next routine began life as a macro and many parameters in it
  1159.  * are used as call-by-reference values.
  1160.  */
  1161. char *
  1162. scan_diff_line (scan_ptr, set_start, set_length, limit, firstchar)
  1163.      char *scan_ptr, **set_start;
  1164.      int *set_length;
  1165.      char *limit;
  1166.      char firstchar;
  1167. {
  1168.   char *line_ptr = scan_ptr + 2;
  1169.  
  1170.   if (!(scan_ptr[0] == (firstchar)
  1171.     && scan_ptr[1] == ' '))
  1172.     fatal ("Bad diff format; incorrect leading line chars");
  1173.  
  1174.   *set_start = line_ptr;
  1175.   while (*line_ptr != '\n') line_ptr++;
  1176.   
  1177.   if (line_ptr >= limit)
  1178.     fatal ("Bad diff format; overflow in parse");
  1179.  
  1180.   /* Don't include newline, but do return the beginning of the
  1181.      next line */
  1182.   *set_length = line_ptr - *set_start;
  1183.  
  1184.   return line_ptr + 1;
  1185. }
  1186.  
  1187. /*
  1188.  * This routine outputs a three way diff passed as a list of
  1189.  * diff3_block's.
  1190.  * The argument MAPPING is indexed by external file number (in the
  1191.  * argument list) and contains the internal file number (from the
  1192.  * diff passed).  This is important because the user expects his
  1193.  * outputs in terms of the argument list number, and the diff passed
  1194.  * may have been done slightly differently (if the first argument in
  1195.  * the argument list was the standard input, for example).
  1196.  */
  1197. void
  1198. output_diff3 (outputfile, diff, mapping)
  1199.      FILE *outputfile;
  1200.      struct diff3_block *diff;
  1201.      int mapping[3];
  1202. {
  1203.   int rev_mapping[3];
  1204.   static int eliminate[3] = { 1, 0, 0};
  1205.   int i;
  1206.   int oddoneout;
  1207.   char *cp;
  1208.   struct diff3_block *ptr;
  1209.   int line;
  1210.   int dontprint;
  1211.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1212.  
  1213.   for (i = 0; i < 3; i++)
  1214.     rev_mapping [mapping[i]] = i;
  1215.  
  1216.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1217.     {
  1218.       char x[2];
  1219.  
  1220.       switch (ptr->correspond)
  1221.     {
  1222.     case DIFF_ALL:
  1223.       x[0] = '\0';
  1224.       dontprint = 3;    /* Print them all */
  1225.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1226.       break;
  1227.     case DIFF_1ST:
  1228.     case DIFF_2ND:
  1229.     case DIFF_3RD:
  1230.       oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1231.         
  1232.       x[0] = oddoneout + '1';
  1233.       x[1] = '\0';
  1234.       dontprint = eliminate [oddoneout];
  1235.       break;
  1236.     default:
  1237.       fatal ("internal: Bad diff type passed to output");
  1238.     }
  1239.       fprintf (outputfile, "====%s\n", x);
  1240.  
  1241.       /* Go 0, 2, 1 if the first and third outputs are equivalent. */
  1242.       for (i = 0; i < 3;
  1243.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1244.     {
  1245.       int realfile = mapping[i];
  1246.       int
  1247.         lowt = D_LOWLINE (ptr, realfile),
  1248.         hight = D_HIGHLINE (ptr, realfile);
  1249.       
  1250.       fprintf (outputfile, "%d:", i + 1);
  1251.       switch (lowt - hight)
  1252.         {
  1253.         case 1:
  1254.           fprintf (outputfile, "%da\n", lowt - 1);
  1255.           break;
  1256.         case 0:
  1257.           fprintf (outputfile, "%dc\n", lowt);
  1258.           break;
  1259.         default:
  1260.           fprintf (outputfile, "%d,%dc\n", lowt, hight);
  1261.           break;
  1262.         }
  1263.  
  1264.       if (i == dontprint) continue;
  1265.  
  1266.       for (line = 0; line < hight - lowt + 1; line++)
  1267.         {
  1268.           fprintf (outputfile, "  ");
  1269.           for (cp = D_RELNUM (ptr, realfile, line);
  1270.            cp < (D_RELNUM (ptr, realfile, line)
  1271.              + D_RELLEN (ptr, realfile, line));
  1272.            cp++)
  1273.         putc (*cp, outputfile);
  1274.           putc ('\n', outputfile);
  1275.         }
  1276.     }
  1277.     }
  1278. }
  1279.  
  1280. /*
  1281.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1282.  * script applies the changes between file's 2 & 3 to file 1.  It
  1283.  * takes the precise format of the ed script to be output from global
  1284.  * variables set during options processing.  Note that it does
  1285.  * destructive things to the set of diff3 blocks it is passed; it
  1286.  * reverses their order (this gets around the problems involved with
  1287.  * changing line numbers in an ed script).
  1288.  *
  1289.  * Note that this routine has the same problem of mapping as the last
  1290.  * one did; the variable MAPPING maps from file number according to
  1291.  * the argument list to file number according to the diff passed.  All
  1292.  * files listed below are in terms of the argument list.
  1293.  *
  1294.  * Also, occasionally this routine needs the real names of the files
  1295.  * on which it works.  Thus file0, file1, and file2 are the filenames
  1296.  * passed on the command line.
  1297.  *
  1298.  * Returns the number of overlaps.
  1299.  *
  1300.  * See options.h for documentation on the global variables which this
  1301.  * routine pays attention to.
  1302.  */
  1303.  
  1304. int
  1305. output_diff3_edscript (outputfile, diff, mapping, file0, file1, file2)
  1306.      FILE *outputfile;
  1307.      struct diff3_block *diff;
  1308.      int mapping[3];
  1309.      char *file0, *file1, *file2;
  1310. {
  1311.   int rev_mapping[3];
  1312.   int i;
  1313.   int leading_dot;
  1314.   int overlap_count = 0;
  1315.   struct diff3_block *newblock, *thisblock;
  1316.   char *cp;
  1317.  
  1318.   leading_dot = 0;
  1319.  
  1320.   for (i = 0; i < 3; i++)
  1321.     rev_mapping [mapping [i]] = i;
  1322.  
  1323.   newblock = reverse_diff3_blocklist (diff);
  1324.  
  1325.   for (thisblock = newblock; thisblock; thisblock = thisblock->next)
  1326.     {
  1327.       /* Must do mapping correctly.  */
  1328.       enum diff_type type
  1329.     = ((thisblock->correspond == DIFF_ALL) ?
  1330.        DIFF_ALL :
  1331.        ((enum diff_type)
  1332.         (((int) DIFF_1ST)
  1333.          + rev_mapping [(int) thisblock->correspond - (int) DIFF_1ST])));
  1334.  
  1335.       /* If we aren't supposed to do this output block, skip it */
  1336.       if (type == DIFF_2ND || type == DIFF_1ST
  1337.       || (type == DIFF_3RD && dont_write_simple)
  1338.       || (type == DIFF_ALL && dont_write_overlap))
  1339.     continue;
  1340.  
  1341.       if (flagging && type == DIFF_ALL)
  1342.     /* Do special flagging */
  1343.     {
  1344.  
  1345.       /* Put in lines from FILE2 with bracket */
  1346.       fprintf (outputfile, "%da\n",
  1347.            D_HIGHLINE (thisblock, mapping [FILE0]));
  1348.       fprintf (outputfile, "=======\n");
  1349.       for (i = 0;
  1350.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1351.            i++)
  1352.         {
  1353.           if (D_RELNUM (thisblock, mapping[FILE2], i)[0] == '.')
  1354.         { leading_dot = 1; fprintf(outputfile, "."); }
  1355.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1356.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1357.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1358.            cp++)
  1359.         putc (*cp, outputfile);
  1360.           putc ('\n', outputfile);
  1361.         }
  1362.       fprintf (outputfile, ">>>>>>> %s\n.\n", file2);
  1363.       overlap_count++;
  1364.  
  1365.       /* Add in code to take care of leading dots, if necessary. */
  1366.       if (leading_dot)
  1367.         {
  1368.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1369.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1370.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1371.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1372.           leading_dot = 0;
  1373.         }
  1374.  
  1375.       /* Put in code to do initial bracket of lines from FILE0  */
  1376.       fprintf (outputfile, "%da\n<<<<<<< %s\n.\n",
  1377.            D_LOWLINE (thisblock, mapping[FILE0]) - 1,
  1378.            file0);
  1379.     }
  1380.       else if (D_NUMLINES (thisblock, mapping [FILE2]) == 0)
  1381.     /* Write out a delete */
  1382.     {
  1383.       if (D_NUMLINES (thisblock, mapping [FILE0]) == 1)
  1384.         fprintf (outputfile, "%dd\n",
  1385.              D_LOWLINE (thisblock, mapping [FILE0]));
  1386.       else
  1387.         fprintf (outputfile, "%d,%dd\n",
  1388.              D_LOWLINE (thisblock, mapping [FILE0]),
  1389.              D_HIGHLINE (thisblock, mapping [FILE0]));
  1390.     }
  1391.       else
  1392.     /* Write out an add or change */
  1393.     {
  1394.       switch (D_NUMLINES (thisblock, mapping [FILE0]))
  1395.         {
  1396.         case 0:
  1397.           fprintf (outputfile, "%da\n",
  1398.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1399.           break;
  1400.         case 1:
  1401.           fprintf (outputfile, "%dc\n",
  1402.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1403.           break;
  1404.         default:
  1405.           fprintf (outputfile, "%d,%dc\n",
  1406.                D_LOWLINE (thisblock, mapping [FILE0]),
  1407.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1408.           break;
  1409.         }
  1410.       for (i = 0;
  1411.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1412.            i++)
  1413.         {
  1414.           if (D_RELNUM (thisblock, mapping [FILE2], i)[0] == '.')
  1415.         { leading_dot = 1; fprintf (outputfile, "."); }
  1416.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1417.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1418.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1419.            cp++)
  1420.         putc (*cp, outputfile);
  1421.           putc ('\n', outputfile);
  1422.         }
  1423.       fprintf (outputfile, ".\n");
  1424.       
  1425.       /* Add in code to take care of leading dots, if necessary. */
  1426.       if (leading_dot)
  1427.         {
  1428.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1429.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1430.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1431.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1432.           leading_dot = 0;
  1433.         }
  1434.     }
  1435.     }
  1436.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1437.   return overlap_count;
  1438. }
  1439.  
  1440. /*
  1441.  * Reverse the order of the list of diff3 blocks.
  1442.  */
  1443. struct diff3_block *
  1444. reverse_diff3_blocklist (diff)
  1445.      struct diff3_block *diff;
  1446. {
  1447.   register struct diff3_block *tmp, *next, *prev;
  1448.  
  1449.   for (tmp = diff, prev = (struct diff3_block *) 0;
  1450.        tmp; tmp = next)
  1451.     {
  1452.       next = tmp->next;
  1453.       tmp->next = prev;
  1454.       prev = tmp;
  1455.     }
  1456.   
  1457.   return prev;
  1458. }
  1459.  
  1460. int
  1461. myread (fd, ptr, size)
  1462.      int fd, size;
  1463.      char *ptr;
  1464. {
  1465.   int result = read (fd, ptr, size);
  1466.   if (result < 0)
  1467.     perror_with_exit ("Read failed");
  1468.   return result;
  1469. }
  1470.  
  1471. VOID *
  1472. xmalloc (size)
  1473.      int size;
  1474. {
  1475.   VOID *result = (VOID *) malloc (size);
  1476.   if (!result)
  1477.     fatal ("Malloc failed");
  1478.   return result;
  1479. }
  1480.  
  1481. VOID *
  1482. xrealloc (ptr, size)
  1483.      VOID *ptr;
  1484.      int size;
  1485. {
  1486.   VOID *result = (VOID *) realloc (ptr, size);
  1487.   if (!result)
  1488.     fatal ("Malloc failed");
  1489.   return result;
  1490. }
  1491.  
  1492. fatal (string)
  1493.      char *string;
  1494. {
  1495.   fprintf (stderr, "%s: %s\n", argv0, string);
  1496.   exit (1);
  1497. }
  1498.  
  1499. perror_with_exit (string)
  1500.      char *string;
  1501. {
  1502.   perror (string);
  1503.   exit (1);
  1504. }
  1505.